package com.hqd.ch03.v47.boot.context.properties.source;

class PrefixedConfigurationPropertySource implements ConfigurationPropertySource {

    private final ConfigurationPropertySource source;

    private final ConfigurationPropertyName prefix;

    PrefixedConfigurationPropertySource(ConfigurationPropertySource source, String prefix) {
        this.source = source;
        this.prefix = ConfigurationPropertyName.of(prefix);
    }

    protected final ConfigurationPropertyName getPrefix() {
        return this.prefix;
    }

    @Override
    public ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) {
        ConfigurationProperty configurationProperty = this.source.getConfigurationProperty(getPrefixedName(name));
        if (configurationProperty == null) {
            return null;
        }
        return ConfigurationProperty.of(configurationProperty.getSource(), name, configurationProperty.getValue(),
                configurationProperty.getOrigin());
    }

    private ConfigurationPropertyName getPrefixedName(ConfigurationPropertyName name) {
        return this.prefix.append(name);
    }

    @Override
    public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) {
        return this.source.containsDescendantOf(getPrefixedName(name));
    }

    @Override
    public Object getUnderlyingSource() {
        return this.source.getUnderlyingSource();
    }

    protected ConfigurationPropertySource getSource() {
        return this.source;
    }

}
